package com.huixue.cn.ztej.controller;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huixue.cn.ztej.bean.ConstructionTeam;
import com.huixue.cn.ztej.bean.EmployApply;
import com.huixue.cn.ztej.bean.EmployHour;
import com.huixue.cn.ztej.bean.Examine;
import com.huixue.cn.ztej.bean.Item;
import com.huixue.cn.ztej.bean.Picture;
import com.huixue.cn.ztej.bean.Results;
import com.huixue.cn.ztej.bean.Section;
import com.huixue.cn.ztej.bean.User;
import com.huixue.cn.ztej.constants.UserUtil;
import com.huixue.cn.ztej.enums.RoleStatus;
import com.huixue.cn.ztej.service.SysConstructionTeamService;
import com.huixue.cn.ztej.service.SysPictureService;
import com.huixue.cn.ztej.service.SysSectionService;
import com.huixue.cn.ztej.service.SysUserService;
import com.huixue.cn.ztej.service.impl.EmployApplyServiceImpl;
import com.huixue.cn.ztej.service.impl.EmployHourServiceImpl;
import com.huixue.cn.ztej.service.impl.ExamineServiceImpl;
import com.huixue.cn.ztej.utils.SystemContents.API_RETURN_STATUS;
import com.huixue.cn.ztej.utils.annotation.RequestMappingName;
import com.huixue.cn.ztej.utils.framwork.JacksonUtil;
import com.huixue.cn.ztej.weixin.bean.OAuthInfo;
import com.huixue.cn.ztej.weixin.util.WeixinHelper;

@Controller
@RequestMapping(value = "/wemployapply")
public class WEmployApplyController extends BaseController{
	@Autowired
	private EmployApplyServiceImpl employApplyServiceImpl;
	
	@Autowired
	private CommonsMultipartResolver multipartResolver;
	
	@Autowired
	private EmployHourServiceImpl employHourServiceImpl;
	
	@Autowired(required = true)
	SysConstructionTeamService sysConstructionTeamService;
	
	@Autowired
	private ExamineServiceImpl examineServiceImpl;
	
	@Autowired(required = true)
	SysUserService sysUserService;
	
	@Autowired(required = true)
	SysPictureService sysPictureService;
	
	@Autowired(required = true)
	SysSectionService sysSectionService;
	
	/**
	 * <p>跳转到添加页面</p>
	 */
	@RequestMappingName(value = "跳转到添加页面")
	@RequestMapping(value = "/wxadd", method = RequestMethod.GET)
	public String wxadd(Model model,HttpServletRequest request) {	
		OAuthInfo aouAuthInfo  = WeixinHelper.getUserOpenId(request);
		//User currentUser = sysUserService.findUserByOpenId(aouAuthInfo.getOpenId(),false);
		User currentUser = sysUserService.findUserByOpenId(aouAuthInfo.getOpenId(),false);
		if(currentUser==null){
			return "/wx/user/noregister";
		}else if(currentUser.getIsAvailable()==UserUtil.DISABLE_YES){
			model.addAttribute("msg", "账号已禁用,请联系管理员");
			return "/wx/message";
		}
		
		if(currentUser.getRoleId()!=null && 
				Integer.valueOf(currentUser.getRoleId()) == RoleStatus.ROLE_2.getRoleId()){
			model.addAttribute("user",currentUser);
			Results constructionteams = sysConstructionTeamService.findAll(Integer.valueOf(currentUser.getProjectID()));
			List<Section> sections = sysSectionService.listSectionByPro(Integer.valueOf(currentUser.getProjectID().trim()));

			List<Item> constructionteamitems = new ArrayList<Item>();
			if(constructionteams.getData()!=null){
				List<ConstructionTeam> list = (List<ConstructionTeam>)(constructionteams.getData());
				if(list!=null && list.size()>0){
					for(int i = 0;i<list.size();i++){
						ConstructionTeam ct = list.get(i);
						Item item = new Item(ct.getTeamId()+"",ct.getName());
						constructionteamitems.add(item);
					}
				}
			}	
			
			List<Item> sectionitems = new ArrayList<Item>();
			if(sections!=null && sections.size()>0){
					for(int i = 0;i<sections.size();i++){
						Section st = sections.get(i);
						Item item = new Item(st.getSecId()+"",st.getName());
						sectionitems.add(item);
						if(currentUser.getSegmentID()!=null && Integer.valueOf(currentUser.getSegmentID())==st.getSecId()){
							model.addAttribute("defalutSecJson",new JacksonUtil().getJson(item));
						}
					}
				}
			
			model.addAttribute("currentUser",currentUser);
			model.addAttribute("constructionteams",new JacksonUtil().getJson(constructionteamitems));
			//得到施工工段json串
			model.addAttribute("sectionitems",new JacksonUtil().getJson(sectionitems));
			
		}else{
			return "/wx/user/noapply";
		}
		return "/wx/employ/employapply";
	}
	
	@RequestMapping("/wxlist")
	public String wxkist(HttpServletResponse response,HttpServletRequest request,Model model){
		User user = new User();
		user.setRoleId(RoleStatus.ROLE_2.getRoleId()+"");
		model.addAttribute("user",user);
		List<EmployApply> list = new ArrayList<EmployApply>();
		if(user.getRoleId().equals(RoleStatus.ROLE_2.getRoleId()+"")){ //工程人员查询
			Map<String, Object> map = new HashMap<String, Object>();
			Results results = employApplyServiceImpl.searchByPage(map, 0, 20);
			model.addAttribute("res",results);
		}
		
		return "/wx/employ/employlist";
	}
	
	
	@RequestMapping(value = "/save",produces="application/json;charset=UTF-8",method=RequestMethod.POST)
	@ResponseBody
	public Results  save(HttpServletRequest request) throws Exception{
		Results results = null;
		EmployApply employApply = new EmployApply();
		String mileageCode = request.getParameter("mileageCode");
		String applyContent = request.getParameter("applyContent");
		String projectId = request.getParameter("projectId");
		String quantities = request.getParameter("quantities");
		String constructionId = request.getParameter("constructionId");
		String constructionName = request.getParameter("constructionName");
		String onstructionPerson = request.getParameter("onstructionPerson");
		String onstructionHour = request.getParameter("onstructionHour");
		String hourPrice = request.getParameter("hourPrice");
		String fee = request.getParameter("fee");
		String isPlan = request.getParameter("isPlan");
		String applyUserId = request.getParameter("applyUserId");
		String frontImage = request.getParameter("frontImage");
		String middleImage = request.getParameter("middleImage");
		String behindImage = request.getParameter("behindImage");
		String pro_id = request.getParameter("pro_id");
		String segment_id = request.getParameter("segment_id");
		
		String ctx = request.getContextPath();
		String t = ctx.replace("/", "\\");
		if(frontImage.startsWith(t)){
			frontImage = frontImage.replace(t, "");
		}
		
		if(middleImage.startsWith(t)){
			middleImage = middleImage.replace(t, "");
		}
		
		if(behindImage.startsWith(t)){
			behindImage = behindImage.replace(t, "");
		}
		
		//相片List
		List<Picture> picList = new ArrayList<Picture>();
		if(frontImage!=null && frontImage.length()>0){
			Picture picture = new Picture(frontImage,0,2);
			picList.add(picture);
		}
		
		if(middleImage!=null && middleImage.length()>0){
			Picture picture = new Picture(middleImage,0,2);
			picList.add(picture);
		}
		
		if(behindImage!=null && behindImage.length()>0){
			Picture picture = new Picture(behindImage,0,2);
			picList.add(picture);
		}

		employApply.setApplyTime(new Date());
		employApply.setMileageCode(mileageCode);
		employApply.setApplyContent(applyContent);
		employApply.setProjectId(Integer.parseInt(projectId));
		employApply.setQuantities(quantities);
		employApply.setConstructionId(Integer.parseInt(constructionId));
		employApply.setConstructionName(constructionName);
		employApply.setOnstructionPerson(onstructionPerson);
		employApply.setApplyUserId(Integer.parseInt(applyUserId));
		employApply.setProId(Integer.parseInt(pro_id));
		employApply.setSegmentId(Integer.parseInt(segment_id));
		
		//employApply.setOnstructionHour(new BigDecimal(onstructionHour));
		employApply.setHourPrice(new BigDecimal(hourPrice));
		//employApply.setFee(new BigDecimal(fee));
		employApply.setIsPlan(Integer.parseInt(isPlan));
		String aa = request.getParameter("list");
		JSONArray ja = JSONArray.parseArray(aa);
		List<EmployHour> list = new ArrayList<EmployHour>();
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH");
		float constructionHour = 0.0f;
		for(int j=0;j<ja.size();j++){
			EmployHour eh = new EmployHour();
			JSONObject jo = (JSONObject)ja.get(j);
			String persons = jo.getString("persons");
			String personNumber = jo.getString("personNumber");
			String startTime = jo.getString("startTime");
			String endTime = jo.getString("endTime");
			String hours = jo.getString("hours");
			String deductHour = jo.getString("deductHour");
			eh.setPersons(persons);
			eh.setPersonNumber(Integer.parseInt(personNumber));
			eh.setStartTime(sd.parse(startTime));
			eh.setEndTime(sd.parse(endTime));
			eh.setHours(Float.parseFloat(hours));
			eh.setDeductHour(Float.parseFloat(deductHour));
			float workHours = Float.valueOf(eh.getHours());
			constructionHour +=workHours*Integer.valueOf(personNumber);
			list.add(eh);
		}
		employApply.setOnstructionHour(new BigDecimal(constructionHour));
		//总费用
		float fees = constructionHour*Float.valueOf(hourPrice);
		employApply.setFee(new BigDecimal(fees));
		
		employApply.setList(list);
		employApply.setPicList(picList);
		
		int applyId = employApplyServiceImpl.insert(employApply);
		results = new Results(API_RETURN_STATUS.NORMAL.value(), "用工申请保存成功！");
		return results; 
	}
	
	 @RequestMapping(value = "/upload")  
	 public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, Model model) {  
		  
	        String path = request.getSession().getServletContext().getRealPath("upload");  
	        System.out.println(path);
	        String fileName = file.getOriginalFilename();  
//	        String fileName = new Date().getTime()+".jpg";  
	       
	        File targetFile = new File(path, fileName);  
	        if(!targetFile.exists()){  
	            targetFile.mkdirs();  
	        }  
	        //保存  
	        try {  
	            file.transferTo(targetFile);  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	        model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);  
	        model.addAttribute("status", 1);
	        return "result";  
	 }     
	 
	 
	 @RequestMapping("/wxgetemploy")
	 public String wxgetemploy(HttpServletResponse response,HttpServletRequest request,String applyId,Model model){
		 	EmployApply employApply = employApplyServiceImpl.selectById(applyId);
		 	
		 	Map<String,Object> map = new HashMap<String,Object>();
		 	map.put("numberId", applyId);
		 	
		 	List<EmployHour> employHourlist = employHourServiceImpl.selectList(map);
		 	model.addAttribute("employApply", employApply);
		 	model.addAttribute("employHourlist", employHourlist);
		 	
		 	//施工队查询
		 	Results teamResult = sysConstructionTeamService.findBySecId(employApply.getConstructionId());
		 	model.addAttribute("teamResult", teamResult);
		 	
		 	//查询申请人
		 	User applyUser = sysUserService.findUserById(employApply.getApplyUserId());
		 	model.addAttribute("applyUser", applyUser);

		 	//查看审批详情
			List<Examine> examineList = examineServiceImpl.selectByApplyId(employApply.getApplyId(),1);
			model.addAttribute("examineList", examineList);
			
			//查询图片
			Picture picture = new Picture(null,Integer.valueOf(applyId),2);
			List<Picture> picList = sysPictureService.listPicturyByApply(picture);
			model.addAttribute("picList", picList);
			
		 	User currentUser = null;
		 	if(request.getSession().getAttribute("currentUser")!=null){
		 		currentUser = (User)request.getSession().getAttribute("currentUser");
		    	model.addAttribute("currentUser", request.getSession().getAttribute("currentUser"));
		    }else{
		    	String userId = request.getParameter("userId");
		    	currentUser = sysUserService.findUserById(Integer.valueOf(userId));
		    	model.addAttribute("currentUser", currentUser);
		    }
		 	
		 	Map<String,Object> searchParams = new HashMap<String,Object>();
			searchParams.put("projectID", employApply.getProId()+"");
			//查找下级审批
			if(employApply.getState()==0){
				searchParams.put("roleId", RoleStatus.ROLE_3.getRoleId()+"");
			}else if(employApply.getState()==3){
				searchParams.put("segmentID", employApply.getSegmentId()+"");
				searchParams.put("roleId", RoleStatus.ROLE_4.getRoleId()+"");
			}else if(employApply.getState()==4){
				searchParams.put("roleId", RoleStatus.ROLE_5.getRoleId()+"");
			}else if(employApply.getState()==5){
				searchParams.put("roleId", RoleStatus.ROLE_6.getRoleId()+"");
			}
			User nextApprovUser = sysUserService.findUserByParams(searchParams);
			model.addAttribute("nextApprovUser", nextApprovUser);
			
			return "/wx/employ/viewemploy";
	}
	
	/**
	 * 申请成功
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/toSuccess",method=RequestMethod.GET)
	public String success(HttpServletRequest request,Model model){
		model.addAttribute("msg", "申请成功");
		return "/wx/message";
	}	

}
